<?php

namespace iBrand\Shop\Backend\Repository;

use iBrand\Shop\Backend\Model\Shop;
use Prettus\Repository\Eloquent\BaseRepository;
use Illuminate\Database\Eloquent\Collection;

class StoreRepository extends BaseRepository
{
	public function model()
	{
		return Shop::class;
	}

	public function getStorePaginated($where = [], $limit = 15, $shops_ids = [])
	{
		if ($shops_ids === false) {
			return new Collection();
		}

		$data = $this->scopeQuery(function ($query) use ($where, $shops_ids) {
			if (is_array($where) && !empty($where)) {
				foreach ($where as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($shops_ids)) {
				$query = $query->whereIn('id', $shops_ids);
			}

			return $query->with('cityInfo')->orderBy('top', 'DESC')->orderBy('id', 'DESC');
		});

		if ($limit == 0) {
			return $data->all();
		} else {
			return $data->paginate($limit);
		}
	}

	public function saveStoreCityShop($shopIds, $activityId)
	{
		$existsIds = $this->model->where('act', $activityId)->get(['id']);
		if (count($existsIds) > 0) {
			$existsIds = $existsIds->toArray();
			$existsIds = array_column($existsIds, 'id');
		}

		if (is_array($existsIds) && !empty($existsIds)) {
			$diff = array_diff($existsIds, $shopIds);
			$this->model->whereIn('id', $diff)->update(['act' => 0]);
		}

		return $this->model->whereIn('id', $shopIds)->update(['act' => $activityId]);
	}
}